<template>
  <div>
    <el-dialog v-bind="$attrs"
               :visible.sync="showDialog"
               :modal-append-to-body="false"
               v-on="$listeners"
               @open="onOpen"
               @close="onClose"
               title="修改用户信息">
      <el-row :gutter="15">
        <el-form ref="elForm" :model="user" :rules="rules" size="medium" label-width="100px">
          <el-col :span="24">
            <!-- 用户头像 -->
            <el-form-item label="用户头像">
              <!-- 头像缩略图 -->
              <pan-thumb :image="user.avatar+''"/>
              <!-- 文件上传按钮 -->
              <el-button type="primary" icon="el-icon-upload" @click="imagecropperShow=true">修改头像</el-button>
              <!--v-show：是否显示上传组件
              自动转换为png格式
              :key：类似于id，如果一个页面多个图片上传控件，可以做区分
              :url：后台上传的url地址 直接调用，并传递文件数据
              field：传递文件数据的对接名，需要和后台接收属性名一致
              @close：关闭上传组件
              @crop-upload-success：上传成功后的回调 -->
              <image-cropper v-show="imagecropperShow"
                             :width="300" :height="300"
                             :key="imagecropperKey"
                             :url="'/api/uploadFile'"
                             field="file"
                             @close="closeImage"
                             @crop-upload-success="cropSuccess"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="user.username" placeholder="请输入用户名" disabled clearable="" :style="{width: '100%'}">
              </el-input>
            </el-form-item>

            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="user.nickname" placeholder="请输入昵称" clearable="" :style="{width: '100%'}">
              </el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="user.email" placeholder="请输入邮箱" clearable="" :style="{width: '100%'}">
              </el-input>
            </el-form-item>

            <el-form-item label="手机号" prop="phoneNumber">
              <el-input v-model="user.phoneNumber" placeholder="请输入手机号" clearable=""
                        :style="{width: '100%'}"></el-input>
            </el-form-item>

          </el-col>

          <el-col :span="12">

            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="user.sex" size="medium">
                <el-radio v-for="(item, index) in sexOptions" :key="index" :label="item.value"
                          :disabled="item.disabled">{{item.label}}
                </el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="部门" prop="departmentId">
              <el-select v-model="user.departmentId" placeholder="请选择部门" clearable
                         :style="{width: '100%'}" value="">
                <el-option v-for="(item, index) in departments" :key="index" :label="item.name"
                           :value="item.id" :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="生日" prop="birth">
              <el-date-picker v-model="user.birth" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                              :style="{width: '100%'}" placeholder="请选择生日" clearable=""></el-date-picker>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

  import ImageCropper from '../../../components/ImageCropper/index'
  import PanThumb from '../../../components/PanThumb/index'
  import { updateUser } from '../../../api/system/users'
  import { deleteFile } from '../../../api/system/aliOss'
  import { saveFile, deleteFileByUrl } from '../../../api/system/file'

  export default {
    inheritAttrs: false,
    components: {
      ImageCropper,
      PanThumb
    },
    //接收父类的传值
    props: {
      updateVisible: {
        type: Boolean,
        default: false
      },
      departments: {
        type: Array,
        default: []
      },
      updateUser: {}
    },

    data () {
      return {
        // 控制弹出框显示隐藏
        showDialog: false,
        imagecropperShow: false, // 是否显示上传组件
        imagecropperKey: 0, // 上传组件id
        image: '',
        oldImage: '',
        //1为确认时不删除当前图片，0为取消时删除当前图片
        isDeleteImage: 0,
        oldUser: {},
        user: {},
        file: {
          url: null,
          type: '',
          fileName: undefined,
          size: undefined,
        },
        rules: {
          username: [{
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }],
          departmentId: [{
            required: true,
            message: '请选择部门',
            trigger: 'change'
          }],
          nickname: [{
            required: true,
            message: '请输入昵称',
            trigger: 'blur'
          }],
          sex: [{
            required: true,
            message: '性别不能为空',
            trigger: 'change'
          }],
          email: [{
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          }],
          phoneNumber: [{
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          }],
          birth: [{
            required: true,
            message: '请选择生日',
            trigger: 'change'
          }],
        },
        field101Action: 'https://jsonplaceholder.typicode.com/posts/',
        field101fileList: [],
        sexOptions: [{
          'label': '男',
          'value': 0
        }, {
          'label': '女',
          'value': 1
        }, {
          'label': '保密',
          'value': 2
        }],
      }
    },
    computed: {},
    watch: {
      // 监听 addOrUpdateVisible 改变
      updateVisible () {
        this.showDialog = this.updateVisible
      },
    },
    created () {
    },
    mounted () {
    },
    methods: {
      onOpen () {
        this.oldImage = this.updateUser.avatar
        this.user = this.updateUser
        this.oldUser = JSON.parse(JSON.stringify(this.user))
      },

      //右上 × 符号
      onClose () {
        if (this.isDeleteImage === 0) {
          if (this.image !== '') {
            this.deleteAvatar(this.image)
          }
        }

        //清空当地弹窗数据
        this.user = {}
        this.image = ''
        this.isDeleteImage = 0
        this.oldImage = ''
        this.$refs['elForm'].resetFields()
        this.$emit('changeShow', 'false')
      },

      //取消按钮
      close () {
        //会执行onClose()
        this.$emit('update:visible', false)
        this.$emit('changeShow', 'false')
      },

      //确认
      handelConfirm () {
        this.$refs['elForm'].validate(valid => {
          if (!valid) {
            return
          }
          //会执行onClose()
          //判断信息是否改变
          if (this.oldUser.avatar !== this.user.avatar
            || this.oldUser.sex !== this.user.sex
            || this.oldUser.status !== this.user.status
            || this.oldUser.departmentId !== this.user.departmentId
            || this.oldUser.nickname !== this.user.nickname
            || this.oldUser.phoneNumber !== this.user.phoneNumber) {
            this.updataUser()
          } else {
            this.$message.error('信息未改变，没有修改')
          }
        })
      },

      field101BeforeUpload (file) {
        let isRightSize = file.size / 1024 / 1024 < 5
        if (!isRightSize) {
          this.$message.error('文件大小超过 5MB')
        }
        return isRightSize
      },

      // 弹出框关闭后触发
      handleClose () {
        // 子组件调用父组件方法，并传递参数
        this.$emit('changeShow', 'false')
      },

      // 上传成功后的回调函数,自动接收返回数据
      cropSuccess (data) {
        this.imagecropperShow = false
        // 上传成功后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
        this.imagecropperKey = this.imagecropperKey + 1
        //上传成功后删除原来的图片
        if (this.image !== '') {
          this.deleteAvatar(this.image)
        }
        //保存上传之前的头像
        this.user.avatar = this.image = data.data.file.url
        this.file = data.data.file
        console.log(this.image)
      },

      //删除之前在阿里云中的图片
      async deleteAvatar (oldImg) {
        deleteFile(oldImg)
      },

      //删除数据库里的文件记录
      async deleteFileInMysql (oldImg) {
        await deleteFileByUrl(oldImg)
      },

      // 关闭上传组件
      closeImage () {
        this.imagecropperShow = false
        // 上传失败后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
        this.imagecropperKey = this.imagecropperKey + 1
      },

      //添加文件记录
      async addfile () {
        await saveFile(this.file)
      },

      //修改用户信息
      updataUser () {
        updateUser(this.user).then(res => {
          if (res) {
            this.$notify.success({
              title: '操作成功',
              message: '信息修改',
            })
            //关闭
            //删除最开始的头像和数据库里的文件记录
            if (this.image !== '') {
              this.deleteAvatar(this.oldImage)
              this.deleteFileInMysql(this.oldImage)
            }
            this.isDeleteImage = 1
            if (this.oldImage !== this.user.avatar) {
              this.addfile()
            }
            //重新调用父类中的方法
            try {
              this.$emit('reFresh')
            } catch (e) {
            }
            this.onClose()
          }
        })
      },
    },
  }

</script>
<style>

</style>
